<?php

namespace Es\Operate;

use Es\Client;
use Es\Exceptions\CommonExceptions;
use Es\Struct\{ConnectStruct,IndexStruct};

class Index extends Client
{
    /**
     * @param ConnectStruct $connect
     * @throws CommonExceptions
     */
    public function __construct(ConnectStruct $connect)
    {
        parent::__construct($connect);
    }

    /**
     * 判断索引是否存在
     * @param string $index
     * @return bool
     */
    public function exist(string $index) : bool
    {
        $body = [
            'index' => $index
        ];
        return self::$client->indices()->exists($body);
    }

    /**
     * 创建索引
     * @param IndexStruct $indexStruct
     * @return bool
     */
    public function create(IndexStruct $indexStruct) : bool
    {
        $response = self::$client->indices()->create($indexStruct->asArray());
        return $this->parseResponse($response, true);

    }

    /**
     * 删除索引
     * @param string $index
     * @return bool
     */
    public function delete(string $index): bool
    {
        $body = [
            'index' => $index
        ];
        $response = self::$client->indices()->delete($body);
        return $this->parseResponse($response);
    }
    /**
     * es特殊响应的判断
     * @param $response
     * @param bool $indexCreate
     * @return bool
     */
    public  function parseResponse($response, bool $indexCreate = false) : bool
    {
        if (!isset($response['acknowledged']) || $response['acknowledged'] === false){
            return  false;
        }
        if ($indexCreate === true){
            if (!isset($response['shards_acknowledged']) || $response['shards_acknowledged'] === false){
                return  false;
            }
        }
        return true;
    }
}
